﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using XChip_Common;
using System.Threading;
using System.IO.Ports;
using System.Text.RegularExpressions;
using XChipTool.Enties;
using SerialPortHelperLib;
using System.Configuration;
using static XChip_Common.XChipUSB;
using System.IO;

namespace XChipTool.Full
{
    public partial class XChip_Flash : DevExpress.XtraEditors.XtraUserControl
    {
        //是否开启打印
        private bool isPrintShow = true;
        //用来定义发送配置文件类 不能使用多线程 使用的话发送类以前的代码都需要修改 目前多建立一个本地串口
        public SerialPort sPortTemp;
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        /// <summary>
        /// 创建上下文同步
        /// </summary>
        private SynchronizationContext context;
        private FlashBase fb;
        private static XChip_Flash _instance;
        private bool isI2C = false;
        string PatchPath = string.Empty;
        string BinPath = string.Empty;
        string i2cPatchPath = string.Empty;
        string i2cBinPath = string.Empty;
        bool isShowMsg = true;
        uint mIndex = 0; //打开的设备序号
        public static XChip_Flash Instance(SerialPort _sPortTemp)
        {
            if (_instance == null)
            {
                _instance = new XChip_Flash(_sPortTemp);
            }
            return _instance;
        }

        public XChip_Flash(SerialPort _sPortTemp)
        {
            sPortTemp = _sPortTemp;
            if (GetConfigValue("IsI2C") == "1")
            {
                isI2C = true;
            }
            
            InitializeComponent();
            // 获取运行目录
            string runningDirectory = Application.StartupPath;
            // 拼接 Lib 文件夹路径
            string libFolderPath = Path.Combine(runningDirectory, "Lib");
            string fileName = "Code_xchip_patch_20250602_200316_32a8d_buffer_flash_burn.txt";
            BinPath = Path.Combine(libFolderPath, fileName);
            PatchLab.Text = fileName;
        }

        private void btnFlashRead_Click(object sender, EventArgs e)
        {
            //I2C
            if (isI2C)
            {
                //uint spi_shift_cnt;
                //uint spi_rxvld_cnt;
                //uint senddata;
                //uint recvdata = 0;
                //uint op_code = 0x03;
                //var flash_address = Convert.ToUInt32(txtBoxFlashAddress.Text, 16);
                //SerialSend.WriteRegister(0x82000000,0x01,null);
                //senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + op_code);
                //SerialSend.WriteRegister(0x82000013, senddata >> 24 & 0xff, null);
                //SerialSend.WriteRegister(0x82000012, senddata >> 16 & 0xff, null);
                //SerialSend.WriteRegister(0x82000011, senddata >> 8 & 0xff, null);
                //SerialSend.WriteRegister(0x82000010, senddata & 0xff, null);
                //Thread.Sleep(10);
                //var aaaa = (3 << 16) + (32 << 8) + (64 << 0);
                ////0x00032040
                //SerialSend.WriteRegister(0x8200000f, (3 << 16) + (32 << 8) + (64 << 0) >> 24 & 0xff, null);
                //SerialSend.WriteRegister(0x8200000d, (3 << 16) + (32 << 8) + (64 << 0) >> 8 & 0xff, null);
                //SerialSend.WriteRegister(0x8200000c, (3 << 16) + (32 << 8) + (64 << 0) & 0xff, null);
                //SerialSend.WriteRegister(0x8200000e, (3 << 16) + (32 << 8) + (64 << 0) >> 16 & 0xff, null);
                //Thread.Sleep(10);

                //for (int i = 0; i < 100; i++)
                //{
                //    var aa =  SerialSend.ReadRegister(0x82000040, null);
                //    if (aa == 0x02)
                //    {
                //        break;
                //    }
                //    Thread.Sleep(10);
                //}
                //SerialSend.WriteRegister(0x82000040, 0x01, null);
                //Thread.Sleep(10);
                //var h = SerialSend.ReadRegister(0x82000023, null);
                //var m1 = SerialSend.ReadRegister(0x82000022, null);
                //var m0 = SerialSend.ReadRegister(0x82000021, null);
                //var l = SerialSend.ReadRegister(0x82000020, null);
                //Thread.Sleep(10);
                //SerialSend.WriteRegister(0x82000040, 0x01, null);
                this.txtBoxFlashData.Text = I2CFlashRead(Convert.ToUInt32(txtBoxFlashAddress.Text, 16));
                return;
            }

            if (IsUsbOpen)
            {
                uint pVule = 0x0;
                bool isbool;
                if (IntPtr.Size == 8)
                {
                    isbool = XChipUSB.UsbFlashRead64(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), ref pVule);
                }
                else
                {
                    isbool = XChipUSB.UsbFlashRead86(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), ref pVule);
                }
                if (isbool)
                {
                    txtBoxFlashData.Text = pVule.ToString("X2");
                }

                return;
            }
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口没有打开");
                return;
            }
            if (!Regex.Match(txtBoxFlashAddress.Text, @"^[A-Za-z0-9]+$").Success)
            {
                return;
            }

            ErasePrecent.EditValue = 0;
            //Fb_SendEvent("Flash操作->读 开始执行\r\n");

            //long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;

            //uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            //uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            //test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
            //uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

            //test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            //uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

            //test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            //uint TXD0_ADDR = (uint)(test_value1 + test_value2);

            //test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
            //uint TXD1_ADDR = (uint)(test_value1 + test_value2);


            //test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
            //uint RXD0_ADDR = (uint)(test_value1 + test_value2);

            //test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
            //uint RXD1_ADDR = (uint)(test_value1 + test_value2);


            //uint flash_address = Convert.ToUInt32(txtBoxFlashAddress.Text, 16);

            //uint spi_shift_cnt;
            //uint spi_rxvld_cnt;
            //uint senddata;
            //uint recvdata = 0;
            //uint op_code = 0x03;

            //FlashBase fb = new FlashBase(sPortTemp);
            //fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
            //fb.SendEvent += Fb_SendEvent;
            //Thread.Sleep(200);
            //senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + op_code);
            //fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            //Thread.Sleep(200);
            //spi_shift_cnt = 64;
            //spi_rxvld_cnt = 32;
            //senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            //fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            //Thread.Sleep(200);

            //fb.ReadRegDataARM(0x11, RXD0_ADDR, ref recvdata, sPortTemp);

            //this.txtBoxFlashData.Text = Convert.ToString(recvdata, 16).ToUpper();
            //Fb_SendEvent("Flash操作->读 执行完成\r\n");

            this.txtBoxFlashData.Text = FlashRead(Convert.ToUInt32(txtBoxFlashAddress.Text, 16));
        }
        private string FlashRead(uint flash_address)
        {
            Fb_SendEvent("Flash操作->读 开始执行\r\n");

            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;

            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
            uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            uint TXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
            uint TXD1_ADDR = (uint)(test_value1 + test_value2);


            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
            uint RXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
            uint RXD1_ADDR = (uint)(test_value1 + test_value2);


            //uint flash_address = Convert.ToUInt32(txtBoxFlashAddress.Text, 16);

            uint spi_shift_cnt;
            uint spi_rxvld_cnt;
            uint senddata;
            uint recvdata = 0;
            uint op_code = 0x03;

            FlashBase fb = new FlashBase(sPortTemp);
            //8200000 写 1 
            fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
            fb.SendEvent += Fb_SendEvent;
            Thread.Sleep(10);
            //读取的地址 + 3
            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + op_code);
            //82000010 写 读取的地址 + 3
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            Thread.Sleep(10);
            spi_shift_cnt = 64;
            spi_rxvld_cnt = 32;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            //8200000c 写 00032040
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            Thread.Sleep(10);
            // 32位读 82000020 
            fb.ReadRegDataARM(0x11, RXD0_ADDR, ref recvdata, sPortTemp);
            Fb_SendEvent("Flash操作->读 执行完成\r\n");
            return Convert.ToString(recvdata, 16).ToUpper();

        }
        private void btnFlashWrite_Click(object sender, EventArgs e)
        {
            if (isI2C)
            {
                //FlashWriteEnable
                //SerialSend.WriteRegister(0x82000013, 0x00, null);
                //SerialSend.WriteRegister(0x82000012, 0x00, null);
                //SerialSend.WriteRegister(0x82000011, 0x00, null);
                //SerialSend.WriteRegister(0x82000010, 0x06, null);
                //bool isbool = false;
                //uint senddata = (3 << 16) + (0 << 8) + (8 << 0);
                //SerialSend.WriteRegister(0x8200000f, senddata >> 24 & 0xff, null);
                //SerialSend.WriteRegister(0x8200000d, senddata >> 8 & 0xff, null);
                //SerialSend.WriteRegister(0x8200000c, senddata & 0xff, null);
                //SerialSend.WriteRegister(0x8200000e, senddata >> 16 & 0xff, null);

                ////SPI_Status();
                ////SerialSend.WriteRegister(0x82000040, 0x01, null);
                ////FlashReadStatus();
                ////SerialSend.WriteRegister(0x82000000, 0x01, null);

                //var h = SerialSend.ReadRegister(0x82000007, null);
                //var m1 = SerialSend.ReadRegister(0x82000006, null);
                //var m0 = SerialSend.ReadRegister(0x82000005, null);
                //var l = SerialSend.ReadRegister(0x82000004, null);

                //var recvdata = (uint)(h << 24 | m1 << 16 | m0 << 8 | l);
                ////senddata = (recvdata & 0xffff3cff + (1 << 8));
                ////SerialSend.WriteRegister(0x82000007, senddata >> 24 & 0xff, null);
                ////SerialSend.WriteRegister(0x82000006, senddata >> 16 & 0xff, null);
                ////SerialSend.WriteRegister(0x82000005, senddata >> 8 & 0xff, null);
                ////SerialSend.WriteRegister(0x82000004, senddata & 0xff, null);

                ////senddata = (((Convert.ToUInt32(txtBoxFlashAddress.Text, 16) & 0xff) << 24) + ((Convert.ToUInt32(txtBoxFlashAddress.Text, 16) & 0xff00) << 8) + ((Convert.ToUInt32(txtBoxFlashAddress.Text, 16) & 0xff0000) >> 8) + 0x39);
                ////SerialSend.WriteRegister(0x82000013, senddata >> 24 & 0xff, null);
                ////SerialSend.WriteRegister(0x82000012, senddata >> 16 & 0xff, null);
                ////SerialSend.WriteRegister(0x82000011, senddata >> 8 & 0xff, null);
                ////SerialSend.WriteRegister(0x82000010, senddata & 0xff, null);
                ////senddata = (3 << 16) + (0 << 8) + (32 << 0);
                ////SerialSend.WriteRegister(0x8200000f, senddata >> 24 & 0xff, null);
                ////SerialSend.WriteRegister(0x8200000d, senddata >> 8 & 0xff, null);
                ////SerialSend.WriteRegister(0x8200000c, senddata & 0xff, null);
                ////SerialSend.WriteRegister(0x8200000e, senddata >> 16 & 0xff, null);
                //isbool = SPI_Status();
                //SerialSend.WriteRegister(0x82000040, 0x01, null);
                ////FlashReadStatus();

                //senddata = (((Convert.ToUInt32(txtBoxFlashAddress.Text, 16) & 0xff) << 24) + ((Convert.ToUInt32(txtBoxFlashAddress.Text, 16) & 0xff00) << 8) + ((Convert.ToUInt32(txtBoxFlashAddress.Text, 16) & 0xff0000) >> 8) + 0x02);
                //SerialSend.WriteRegister(0x82000013, senddata >> 24 & 0xff, null);
                //SerialSend.WriteRegister(0x82000012, senddata >> 16 & 0xff, null);
                //SerialSend.WriteRegister(0x82000011, senddata >> 8 & 0xff, null);
                //SerialSend.WriteRegister(0x82000010, senddata & 0xff, null);

                //SerialSend.WriteRegister(0x82000017, Convert.ToUInt32(txtBoxFlashData.Text, 16) >> 24 & 0xff, null);
                //SerialSend.WriteRegister(0x82000016, Convert.ToUInt32(txtBoxFlashData.Text, 16) >> 16 & 0xff, null);
                //SerialSend.WriteRegister(0x82000015, Convert.ToUInt32(txtBoxFlashData.Text, 16) >> 8 & 0xff, null);
                //SerialSend.WriteRegister(0x82000014, Convert.ToUInt32(txtBoxFlashData.Text, 16) & 0xff, null);
                //senddata = (3 << 16) + (0 << 8) + (64 << 0);
                //SerialSend.WriteRegister(0x8200000f, senddata >> 24 & 0xff, null);
                //SerialSend.WriteRegister(0x8200000d, senddata >> 8 & 0xff, null);
                //SerialSend.WriteRegister(0x8200000c, senddata & 0xff, null);
                //SerialSend.WriteRegister(0x8200000e, senddata >> 16 & 0xff, null);
                //isbool = SPI_Status();
                //SerialSend.WriteRegister(0x82000040, 0x01, null);
                ////FlashReadStatus();
                I2CFlashWrite(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), Convert.ToUInt32(txtBoxFlashData.Text, 16));
                return;
            }


            if (IsUsbOpen)
            {
                bool isbool;
                if (IntPtr.Size == 8)
                {
                    isbool = XChipUSB.UsbFlashWrite64(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), Convert.ToUInt32(txtBoxFlashData.Text, 16));
                }
                else
                {
                    isbool = XChipUSB.UsbFlashWrite86(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), Convert.ToUInt32(txtBoxFlashData.Text, 16));
                }
                if (isbool)
                {
                    //txtBoxFlashData.Text = pVule.ToString("X2");
                }

                return;
            }


            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口没有打开");
                return;
            }
            if (!Regex.Match(txtBoxFlashAddress.Text, @"^[A-Za-z0-9]+$").Success && !Regex.Match(txtBoxFlashData.Text, @"^[A-Za-z0-9]+$").Success)
            {
                return;
            }
            ErasePrecent.EditValue = 0;
            //Fb_SendEvent("Flash操作->写 执行开始\r\n");

            //long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;

            //uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            //uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            //test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
            //uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

            //test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            //uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

            //test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            //uint TXD0_ADDR = (uint)(test_value1 + test_value2);

            //test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
            //uint TXD1_ADDR = (uint)(test_value1 + test_value2);


            //test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
            //uint RXD0_ADDR = (uint)(test_value1 + test_value2);

            //test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
            //uint RXD1_ADDR = (uint)(test_value1 + test_value2);

            //uint flash_address = Convert.ToUInt32(txtBoxFlashAddress.Text, 16);
            //uint flash_data = Convert.ToUInt32(txtBoxFlashData.Text, 16);

            //uint spi_shift_cnt;
            //uint spi_rxvld_cnt;
            //uint senddata;
            //uint recvdata = 0;

            ////spi mode
            //FlashBase fb = new FlashBase(sPortTemp);
            //fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
            //fb.SendEvent += Fb_SendEvent;
            //Thread.Sleep(200);
            ////spi cs 片选
            //uint spi_cs = 1;
            //fb.ReadRegDataARM(0x11, CONTROL_ADDR, ref recvdata, sPortTemp);
            //senddata = recvdata & 0xffff3cff;
            //senddata = senddata + (spi_cs << 8);
            //fb.SendRegDataARM(0x1, CONTROL_ADDR, senddata, sPortTemp);
            //recvdata = fb.FlashReadStatus(sPortTemp);
            //fb.FlashWriteEnable(sPortTemp);
            //recvdata = fb.FlashReadStatus(sPortTemp);
            ////unprotected
            //senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0x39);
            //fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            ////SHIFT_CONTROL
            //spi_shift_cnt = 32;
            //spi_rxvld_cnt = 0;
            //senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            //fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            //Thread.Sleep(200);
            //recvdata = fb.FlashReadStatus(sPortTemp);
            //fb.FlashWriteEnable(sPortTemp);
            //recvdata = fb.FlashReadStatus(sPortTemp);
            ////TXD0
            //senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0x02);
            //fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            ////TXD1
            //senddata = flash_data;
            //fb.SendRegDataARM(0x1, TXD1_ADDR, senddata, sPortTemp);
            ////SHIFT_CONTROL
            //spi_shift_cnt = 64;
            //spi_rxvld_cnt = 0;
            //senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            //fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            //Thread.Sleep(200);
            //Fb_SendEvent("Flash操作->写 执行成功\r\n");

            FlashWrite(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), Convert.ToUInt32(txtBoxFlashData.Text, 16));
        }
        private async void UpdateProgressAsync64(bool isbool)
        {
            while (isbool) // 假设isbool是一个控制循环是否继续的布尔变量  
            {
                XChipUSB.CallBackInfo info = XChipUSB.GetProgressInfo64();
                binPBC.Position = info.progress; // 假设binPBC是一个进度条控件  

                if (info.progress == 100 && info.result >= 0)
                {
                    // 读写完成跳出  
                    MessageBox.Show("完成");
                    SerialSend.WriteRegister(0x80500137, 0xce, sPortTemp);
                    break;
                }
                else if (info.result < 0)
                {
                    // 读写异常跳出  
                    MessageBox.Show("异常跳出");
                    break;
                }

                // 使用Task.Delay代替Thread.Sleep来避免阻塞UI线程  
                await Task.Delay(20); // 延迟20毫秒后再检查进度，这不会阻塞UI线程  
            }
        }
        private async void UpdateProgressAsync86(bool isbool)
        {
            while (isbool) // 假设isbool是一个控制循环是否继续的布尔变量  
            {
                XChipUSB.CallBackInfo info = XChipUSB.GetProgressInfo86();
                binPBC.Position = info.progress; // 假设binPBC是一个进度条控件  

                if (info.progress == 100 && info.result >= 0)
                {
                    // 读写完成跳出  
                    MessageBox.Show("完成");
                    SerialSend.WriteRegister(0x80500137, 0xce, sPortTemp);
                    break;
                }
                else if (info.result < 0)
                {
                    // 读写异常跳出  
                    MessageBox.Show("异常跳出");
                    break;
                }

                // 使用Task.Delay代替Thread.Sleep来避免阻塞UI线程  
                await Task.Delay(20); // 延迟20毫秒后再检查进度，这不会阻塞UI线程  
            }
        }
        private async void btnFlashWriteFile_Click(object sender, EventArgs e)
        {
            if (IsUsbOpen)
            {
                if (!IsUsbOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("USB未打开");
                    return;
                }
                
                if (textEdit1.Text != null)
                {
                    bool isbool;
                    binPBC.Visible = true;
                    binPBC.Properties.Minimum = 0;
                    binPBC.Properties.Maximum = 100;
                    binPBC.Properties.Step = 1;
                    binPBC.Position = 0;
                    binPBC.Properties.ShowTitle = true;
                    binPBC.Properties.PercentView = true;
                    if (IntPtr.Size == 8)
                    {
                       
                        bool success =  await WriteFileAsync(textEdit1.Text, 0, binPBC);
                        if (success)
                        {
                            MessageBox.Show("文件写入成功！");
                        }
                        else
                        {
                            MessageBox.Show("文件写入失败！");
                        }
                    }
                    else
                    {
                        bool success = await WriteFileAsync(textEdit1.Text, 0, binPBC);
                        if (success)
                        {
                            MessageBox.Show("文件写入成功！");
                        }
                        else
                        {
                            MessageBox.Show("文件写入失败！");
                        }
                    }

                }
                else
                {
                    MessageBox.Show("请选择文件");
                }


            }
        }

        private void FlashWrite(uint flash_address, uint flash_data)
        {
            Fb_SendEvent("Flash操作->写 执行开始\r\n");

            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;

            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
            uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            uint TXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
            uint TXD1_ADDR = (uint)(test_value1 + test_value2);


            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
            uint RXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
            uint RXD1_ADDR = (uint)(test_value1 + test_value2);

            //uint flash_address = Convert.ToUInt32(txtBoxFlashAddress.Text, 16);
            //uint flash_data = Convert.ToUInt32(txtBoxFlashData.Text, 16);

            uint spi_shift_cnt;
            uint spi_rxvld_cnt;
            uint senddata;
            uint recvdata = 0;

            //spi mode
            FlashBase fb = new FlashBase(sPortTemp);
            //0x82000000 写 1
            fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
            fb.SendEvent += Fb_SendEvent;
            Thread.Sleep(200);
            //spi cs 片选
            uint spi_cs = 1;
            //0x82000004 32位读  & 0xffff3cff + (1 << 8)
            fb.ReadRegDataARM(0x11, CONTROL_ADDR, ref recvdata, sPortTemp);
            senddata = recvdata & 0xffff3cff;
            senddata = senddata + (spi_cs << 8);
            //0x82000004 写 0x82000004 32位读  & 0xffff3cff + (1 << 8)
            fb.SendRegDataARM(0x1, CONTROL_ADDR, senddata, sPortTemp);
            recvdata = fb.FlashReadStatus(sPortTemp);
            fb.FlashWriteEnable(sPortTemp);
            recvdata = fb.FlashReadStatus(sPortTemp);
            //unprotected
            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0x39);
            //0x82000010 写 要写的地址 + 0x39 
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            //SHIFT_CONTROL
            spi_shift_cnt = 32;
            spi_rxvld_cnt = 0;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            //0x8200000c 写 (3 << 16) + (0 << 8) + (32 << 0);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            Thread.Sleep(200);
            recvdata = fb.FlashReadStatus(sPortTemp);
            fb.FlashWriteEnable(sPortTemp);
            recvdata = fb.FlashReadStatus(sPortTemp);
            //TXD0
            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0x02);
            //0x82000010
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            //TXD1
            senddata = flash_data;
            //0x82000014
            fb.SendRegDataARM(0x1, TXD1_ADDR, senddata, sPortTemp);
            //SHIFT_CONTROL
            spi_shift_cnt = 64;
            spi_rxvld_cnt = 0;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            //0x8200000c
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            Thread.Sleep(200);
            Fb_SendEvent("Flash操作->写 执行成功\r\n");
        }

        private void Fb_SendEvent(string msg)
        {
            if (isPrintShow)
            {
                context.Post(t =>
                {
                    //操作
                    if (textBox_disp.GetLineFromCharIndex(textBox_disp.Text.Length) > 10000)
                    {
                        textBox_disp.Text = string.Empty;
                    }
                    //追加的形式添加到文本框末端，并滚动到最后。     
                    this.textBox_disp.AppendText(msg);
                    this.textBox_disp.AppendText("\r\n");
                    this.textBox_disp.SelectionStart = textBox_disp.Text.Length;
                    this.textBox_disp.ScrollToCaret();

                }, msg);
            }
        }

        private void XChip_Flash_Load(object sender, EventArgs e)
        {
            //如果是这样，我们可以通过创建SynchronizationContext来简化
            if (context == null)
            {
                context = SynchronizationContext.Current;
            }
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            {
                groupControl8.Visible = false;
                binPBC.Visible = true;
                if (GetConfigValue("IsI2C") == "1")
                {
                    groupControl8.Visible = false;
                    groupControl1.Visible = true;
                }
            }
            else
            {
                groupControl8.Visible = false;
                binPBC.Visible = false;
            }
        }
        private string GetConfigValue(string strKey)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;

            return settings[strKey].Value;
        }
        private void btnFlashErase_Click(object sender, EventArgs e)
        {
            if (isI2C)
            {
                Fb_SendEvent("Flash操作->擦除 执行开始\r\n");
                bool isbool = false;
                SerialSend.WriteRegister(0x82000000, 0x01, null);
                //FlashWriteEnable
                SerialSend.WriteRegister(0x82000013, 0x00, null);
                SerialSend.WriteRegister(0x82000012, 0x00, null);
                SerialSend.WriteRegister(0x82000011, 0x00, null);
                SerialSend.WriteRegister(0x82000010, 0x06, null);

                uint senddatai2c = (3 << 16) + (0 << 8) + (8 << 0);
                SerialSend.WriteRegister(0x8200000f, senddatai2c >> 24 & 0xff, null);
                SerialSend.WriteRegister(0x8200000d, senddatai2c >> 8 & 0xff, null);
                SerialSend.WriteRegister(0x8200000c, senddatai2c & 0xff, null);
                SerialSend.WriteRegister(0x8200000e, senddatai2c >> 16 & 0xff, null);
                isbool = FlashReadStatus();
                Thread.Sleep(200);
                isbool = FlashReadStatus();
                senddatai2c = (((Convert.ToUInt32(txtBoxFlashAddress.Text, 16) & 0xff) << 24) + ((Convert.ToUInt32(txtBoxFlashAddress.Text, 16) & 0xff00) << 8) + ((Convert.ToUInt32(txtBoxFlashAddress.Text, 16) & 0xff0000) >> 8) + 0x20);
                SerialSend.WriteRegister(0x82000013, senddatai2c >> 24 & 0xff, null);
                SerialSend.WriteRegister(0x82000012, senddatai2c >> 16 & 0xff, null);
                SerialSend.WriteRegister(0x82000011, senddatai2c >> 8 & 0xff, null);
                SerialSend.WriteRegister(0x82000010, senddatai2c & 0xff, null);

                senddatai2c = (3 << 16) + (0 << 8) + (32 << 0);
                SerialSend.WriteRegister(0x8200000f, senddatai2c >> 24 & 0xff, null);
                SerialSend.WriteRegister(0x8200000d, senddatai2c >> 8 & 0xff, null);
                SerialSend.WriteRegister(0x8200000c, senddatai2c & 0xff, null);
                SerialSend.WriteRegister(0x8200000e, senddatai2c >> 16 & 0xff, null);
                Fb_SendEvent("Flash操作->擦除 执行完成\r\n");
                return;
            }
            if (IsUsbOpen)
            {
                Fb_SendEvent("Flash操作->擦除 执行开始\r\n");
                bool isFlash = false;
                if (IntPtr.Size == 8)
                {
                    var aaa = Convert.ToUInt32(txtBoxFlashAddress.Text, 16);
                    isFlash = XChipUSB.UsbFlashErase64(Convert.ToUInt32(txtBoxFlashAddress.Text, 16));
                }
                else
                {
                    isFlash = XChipUSB.UsbFlashErase86(Convert.ToUInt32(txtBoxFlashAddress.Text, 16));
                }
                if (isFlash)
                {
                    Fb_SendEvent("Flash操作->擦除 执行完成\r\n");
                    txtBoxFlashData.Text = string.Empty;
                }
                else
                {
                    Fb_SendEvent("Flash操作->擦除 执行失败\r\n");
                }
                return;
            }
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口没有打开");
                return;
            }
            if (!Regex.Match(txtBoxFlashAddress.Text, @"^[A-Za-z0-9]+$").Success)
            {
                return;
            }
            ErasePrecent.EditValue = 0;
            Fb_SendEvent("Flash操作->擦除 执行开始\r\n");
            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;

            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
            uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            uint TXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
            uint TXD1_ADDR = (uint)(test_value1 + test_value2);


            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
            uint RXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
            uint RXD1_ADDR = (uint)(test_value1 + test_value2);

            uint flash_address = Convert.ToUInt32(txtBoxFlashAddress.Text, 16);
            //uint flash_data = Convert.ToUInt32(txtBoxFlashData.Text, 16);

            uint spi_shift_cnt;
            uint spi_rxvld_cnt;
            uint senddata;
            uint recvdata = 0;
            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
            fb.SendEvent += Fb_SendEvent;

            fb.FlashWriteEnable(sPortTemp);
            recvdata = fb.FlashReadStatus(sPortTemp);
            //unprotected
            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0x39);
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            //SHIFT_CONTROL
            spi_shift_cnt = 32;
            spi_rxvld_cnt = 0;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            Thread.Sleep(200);

            recvdata = fb.FlashReadStatus(sPortTemp);
            fb.FlashWriteEnable(sPortTemp);
            recvdata = fb.FlashReadStatus(sPortTemp);
            //TXD0
            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0x20);
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            //SHIFT_CONTROL
            spi_shift_cnt = 32;
            spi_rxvld_cnt = 0;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            Fb_SendEvent("Flash操作->擦除 执行完成\r\n");
            txtBoxFlashData.Text = string.Empty;
        }

        private void btnReadID_Click(object sender, EventArgs e)
        {


            //if (!Regex.Match(txtBoxFlashAddress.Text, @"^[A-Za-z0-9]+$").Success)
            //{
            //    return;
            //}
            ErasePrecent.EditValue = 0;
            Fb_SendEvent("Flash操作->读ReadID 执行开始\r\n");

            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;
            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
            uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            uint TXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
            uint TXD1_ADDR = (uint)(test_value1 + test_value2);


            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
            uint RXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
            uint RXD1_ADDR = (uint)(test_value1 + test_value2);

            uint spi_shift_cnt;
            uint spi_rxvld_cnt;
            uint senddata;
            uint recvdata = 0;
            uint op_code = 0x90;
            if (isI2C)
            {
                SerialSend.WriteRegister(0x82000010, 0x90, sPortTemp);
                SerialSend.WriteRegister(0x82000011, 0x00, sPortTemp);
                SerialSend.WriteRegister(0x82000012, 0x00, sPortTemp);
                SerialSend.WriteRegister(0x82000013, 0x00, sPortTemp);
                Thread.Sleep(100);
                SerialSend.WriteRegister(0x8200000c, 0x40, sPortTemp);
                SerialSend.WriteRegister(0x8200000d, 0x20, sPortTemp);
                SerialSend.WriteRegister(0x8200000e, 0x03, sPortTemp);
                SerialSend.WriteRegister(0x8200000f, 0x00, sPortTemp);
                Thread.Sleep(100);
                this.txtBoxFlashData.Text = (SerialSend.ReadRegister(0x82000023, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000022, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000021, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000020, sPortTemp)).ToString("X2");
                Fb_SendEvent("Flash操作->读ReadID 执行结束\r\n");
                return;
            }
            if (IsUsbOpen)
            {
                //XChipUSB.UsbFlashWrite64(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), Convert.ToUInt32(txtBoxFlashData.Text, 16));
                //XChipUSB.UsbFlashRead64(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), ref pVule);

                SerialSend.WriteRegister(0x82000010, 0x90, sPortTemp);
                SerialSend.WriteRegister(0x82000011, 0x00, sPortTemp);
                SerialSend.WriteRegister(0x82000012, 0x00, sPortTemp);
                SerialSend.WriteRegister(0x82000013, 0x00, sPortTemp);
                Thread.Sleep(100);
                SerialSend.WriteRegister(0x8200000c, 0x40, sPortTemp);
                SerialSend.WriteRegister(0x8200000d, 0x20, sPortTemp);
                SerialSend.WriteRegister(0x8200000e, 0x03, sPortTemp);
                SerialSend.WriteRegister(0x8200000f, 0x00, sPortTemp);
                Thread.Sleep(100);
                this.txtBoxFlashData.Text = (SerialSend.ReadRegister(0x82000023, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000022, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000021, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000020, sPortTemp)).ToString("X2");

                //this.txtBoxFlashData.Text = Convert.ToString(recvdata, 16).ToUpper();
                Fb_SendEvent("Flash操作->读ReadID 执行结束\r\n");
                return;
            }
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口没有打开");
                return;
            }
            FlashBase fb = new FlashBase(sPortTemp);
            //fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
            fb.SendEvent += Fb_SendEvent;
            //spi cs 片选
            uint spi_cs = 1;
            fb.ReadRegDataARM(0x11, CONTROL_ADDR, ref recvdata, sPortTemp);
            //Fb_SendEvent($"Flash操作->读{CONTROL_ADDR.ToString("X2")}值{recvdata.ToString("X2")} 执行结束\r\n");
            senddata = recvdata & 0xffff3cff;
            senddata = senddata + (spi_cs << 8);
            fb.SendRegDataARM(0x1, CONTROL_ADDR, senddata, sPortTemp);
            //Fb_SendEvent($"Flash操作->写{CONTROL_ADDR.ToString("X2")}值{senddata.ToString("X2")} 执行结束\r\n");
            //TXD0
            senddata = op_code;
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            //Fb_SendEvent($"Flash操作->写{TXD0_ADDR.ToString("X2")}值{senddata.ToString("X2")} 执行结束\r\n");
            //SHIFT_CONTROL
            spi_shift_cnt = 64;
            spi_rxvld_cnt = 32;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            //Fb_SendEvent($"Flash操作->写{SHIFT_ADDR.ToString("X2")}值{senddata.ToString("X2")} 执行结束\r\n");
            Thread.Sleep(200);
            fb.ReadRegDataARM(0x11, RXD0_ADDR, ref recvdata, sPortTemp);
            //Fb_SendEvent($"Flash操作->读{RXD0_ADDR.ToString("X2")}值{recvdata.ToString("X2")} 执行结束\r\n");
            this.txtBoxFlashData.Text = Convert.ToString(recvdata, 16).ToUpper();
            Fb_SendEvent("Flash操作->读ReadID 执行结束\r\n");
        }

        private void simpleButton7_Click(object sender, EventArgs e)
        {
            WaitBefore.Start("请耐心等待...", "正在努力加载中");
            try
            {
                if (isI2C)
                {
                    //82000004  32位写82000004 32位读 & 0xffff3cff + (1 << 8)
                    var h = SerialSend.ReadRegister(0x82000007, null);
                    var m1 = SerialSend.ReadRegister(0x82000006, null);
                    var m0 = SerialSend.ReadRegister(0x82000005, null);
                    var l = SerialSend.ReadRegister(0x82000004, null);

                    var recvdatai2C = (uint)(h << 24 | m1 << 16 | m0 << 8 | l);

                    var senddatai2c = (recvdatai2C & 0xffff3cff + (1 << 8));
                    SerialSend.WriteRegister(0x82000007, senddatai2c >> 24 & 0xff, null);
                    SerialSend.WriteRegister(0x82000006, senddatai2c >> 16 & 0xff, null);
                    SerialSend.WriteRegister(0x82000005, senddatai2c >> 8 & 0xff, null);
                    SerialSend.WriteRegister(0x82000004, senddatai2c & 0xff, null);
                    //82000010 32位写 9F
                    SerialSend.WriteRegister(0x82000013, 0, null);
                    SerialSend.WriteRegister(0x82000012, 0, null);
                    SerialSend.WriteRegister(0x82000011, 0, null);
                    SerialSend.WriteRegister(0x82000010, 0x9f, null);
                    //8200000c 32位写  (3 << 16) + (32 << 8) + (64 << 0);
                    senddatai2c = (3 << 16) + (0 << 8) + (64 << 0);
                    SerialSend.WriteRegister(0x8200000f, senddatai2c >> 24 & 0xff, null);
                    SerialSend.WriteRegister(0x8200000d, senddatai2c >> 8 & 0xff, null);
                    SerialSend.WriteRegister(0x8200000c, senddatai2c & 0xff, null);
                    SerialSend.WriteRegister(0x8200000e, senddatai2c >> 16 & 0xff, null);
                    //82000020 32位读得出结果
                    h = SerialSend.ReadRegister(0x82000023, null);
                    m1 = SerialSend.ReadRegister(0x82000022, null);
                    m0 = SerialSend.ReadRegister(0x82000021, null);
                    l = SerialSend.ReadRegister(0x82000020, null);
                    recvdatai2C = (uint)(h << 24 | m1 << 16 | m0 << 8 | l);
                    var kbytestri2c = (Math.Pow(2, (recvdatai2C >> 16 & 0xff)) / 1024);
                    if (kbytestri2c != 0xff && kbytestri2c != 0 && kbytestri2c % 1 == 0 && recvdatai2C != 0xffffffff)
                    {
                        List<TreeListValue> listi2c = new List<TreeListValue>();
                        listi2c.Add(new TreeListValue() { DisplayMember = $"{kbytestri2c}k", ValueMember = $"{kbytestri2c * 1024}" });
                        listi2c.Add(new TreeListValue() { DisplayMember = "4M", ValueMember = $"{4 * 1024 * 1024}" });
                        listi2c.Add(new TreeListValue() { DisplayMember = "8M", ValueMember = $"{8 * 1024 * 1024}" });
                        comboBoxFlashSize.Properties.DataSource = listi2c;
                        comboBoxFlashSize.Properties.ValueMember = "ValueMember";
                        comboBoxFlashSize.Properties.DisplayMember = "DisplayMember";

                        comboBoxFlashSize.ItemIndex = 0;
                        WaitBefore.Close();
                        return;
                    }
                    uint startone = 0x0;
                    uint starttwo = 0x4;
                    uint startthree = 0x8;
                    uint startfour = 0xc;
                    var one = I2CFlashRead(startone);
                    var two = I2CFlashRead(starttwo);
                    var three = I2CFlashRead(startthree);
                    var four = I2CFlashRead(startfour);

                    if (one == "FFFFFFFF"
                        && two == "FFFFFFFF"
                        && three == "FFFFFFFF"
                        && four == "FFFFFFFF")
                    {
                        I2CFlashWrite(startone, 0x00010203);
                        I2CFlashWrite(starttwo, 0x04050607);
                        I2CFlashWrite(startthree, 0x08090a0b);
                        I2CFlashWrite(startfour, 0x0c0d0e0f);
                        one = "00010203";
                        two = "04050607";
                        three = "08090a0b";
                        four = "0c0d0e0f";
                    }

                    int kbyte = 64;
                    one = I2CFlashRead(startone);
                    two = I2CFlashRead(starttwo);
                    three = I2CFlashRead(startthree);
                    four = I2CFlashRead(startfour);
                    if (one == "FFFFFFFF"
                         && two == "FFFFFFFF"
                         && three == "FFFFFFFF"
                         && four == "FFFFFFFF")
                    {
                        Fb_SendEvent("Flash操作->容量检测失败 请先SPI使能\r\n");
                        return;
                    }
                    for (uint i = 0x10000; i < 0x400000; i *= 2)
                    {
                        if (I2CFlashRead(i) == one
                            && I2CFlashRead(i + 0x4) == two
                            && I2CFlashRead(i + 0x8) == three
                            && I2CFlashRead(i + 0xc) == four)
                        {
                            break;
                        }
                        kbyte *= 2;
                    }
                    List<TreeListValue> list = new List<TreeListValue>();
                    list.Add(new TreeListValue() { DisplayMember = $"{kbyte}k", ValueMember = $"{kbyte * 1024}" });
                    list.Add(new TreeListValue() { DisplayMember = "4M", ValueMember = $"{4 * 1024 * 1024}" });
                    list.Add(new TreeListValue() { DisplayMember = "8M", ValueMember = $"{8 * 1024 * 1024}" });
                    comboBoxFlashSize.Properties.DataSource = list;
                    comboBoxFlashSize.Properties.ValueMember = "ValueMember";
                    comboBoxFlashSize.Properties.DisplayMember = "DisplayMember";

                    comboBoxFlashSize.ItemIndex = 0;
                    WaitBefore.Close();
                    return;
                }
                if (IsUsbOpen)
                {
                    //XChipUSB.UsbFlashWrite64(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), Convert.ToUInt32(txtBoxFlashData.Text, 16));
                    //XChipUSB.UsbFlashRead64(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), ref pVule);

                    SerialSend.WriteRegister(0x82000010, 0x9f, sPortTemp);
                    SerialSend.WriteRegister(0x82000011, 0x00, sPortTemp);
                    SerialSend.WriteRegister(0x82000012, 0x00, sPortTemp);
                    SerialSend.WriteRegister(0x82000013, 0x00, sPortTemp);
                    Thread.Sleep(100);
                    SerialSend.WriteRegister(0x8200000c, 0x40, sPortTemp);                                  
                    SerialSend.WriteRegister(0x8200000d, 0x20, sPortTemp);
                    SerialSend.WriteRegister(0x8200000e, 0x03, sPortTemp);
                    SerialSend.WriteRegister(0x8200000f, 0x00, sPortTemp);
                    Thread.Sleep(100);
                    var aaa = Convert.ToUInt32(((SerialSend.ReadRegister(0x82000023, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000022, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000021, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000020, sPortTemp)).ToString("X2")), 16);
                    var kbytestrUSB = (Math.Pow(2, (Convert.ToUInt32(((SerialSend.ReadRegister(0x82000023, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000022, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000021, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000020, sPortTemp)).ToString("X2")), 16) >> 16 & 0xff)) / 1024);
                    if (kbytestrUSB != 0xff && kbytestrUSB != 0 && kbytestrUSB % 1 == 0 && aaa != 0xffffffff)
                    {
                        List<TreeListValue> list = new List<TreeListValue>();
                        list.Add(new TreeListValue() { DisplayMember = $"{kbytestrUSB}k", ValueMember = $"{kbytestrUSB * 1024}" });
                        list.Add(new TreeListValue() { DisplayMember = "4M", ValueMember = $"{4 * 1024 * 1024}" });
                        list.Add(new TreeListValue() { DisplayMember = "8M", ValueMember = $"{8 * 1024 * 1024}" });
                        comboBoxFlashSize.Properties.DataSource = list;
                        comboBoxFlashSize.Properties.ValueMember = "ValueMember";
                        comboBoxFlashSize.Properties.DisplayMember = "DisplayMember";

                        comboBoxFlashSize.ItemIndex = 0;
                        WaitBefore.Close();
                        return;
                    }
                    else
                    {
                        uint startone = 0x0;
                        uint starttwo = 0x4;
                        uint startthree = 0x8;
                        uint startfour = 0xc;
                        uint one = 0;
                        uint two = 0;
                        uint three = 0;
                        uint four = 0;
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbFlashRead64(startone, ref one);
                        }
                        else
                        {
                            XChipUSB.UsbFlashRead86(startone, ref one);
                        }
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbFlashRead64(starttwo, ref two);
                        }
                        else
                        {
                            XChipUSB.UsbFlashRead86(starttwo, ref two);
                        }
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbFlashRead64(startthree, ref three);
                        }
                        else
                        {
                            XChipUSB.UsbFlashRead86(startthree, ref three);
                        }
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbFlashRead64(startfour, ref four);
                        }
                        else
                        {
                            XChipUSB.UsbFlashRead86(startfour, ref four);
                        }
                        if (one.ToString("X2") == "FFFFFFFF"
                            && two.ToString("X2") == "FFFFFFFF"
                            && three.ToString("X2") == "FFFFFFFF"
                            && four.ToString("X2") == "FFFFFFFF")
                        {
                            FlashWrite(startone, 0x00010203);
                            FlashWrite(starttwo, 0x04050607);
                            FlashWrite(startthree, 0x08090a0b);
                            FlashWrite(startfour, 0x0c0d0e0f);
                            one = 0x00010203;
                            two = 0x04050607;
                            three = 0x08090a0b;
                            four = 0x0c0d0e0f;
                        }
                        int kbyte = 64;
                        uint flashi = 0;
                        if (IntPtr.Size == 8)
                        {

                            for (uint i = 0x10000; i < 0x400000; i *= 2)
                            {
                                XChipUSB.UsbFlashRead64(i, ref flashi);
                                if (flashi == one)
                                {
                                    XChipUSB.UsbFlashRead64(i + 0x4, ref flashi);
                                    if (flashi == two)
                                    {
                                        XChipUSB.UsbFlashRead64(i + 0x8, ref flashi);
                                        if (flashi == three)
                                        {
                                            XChipUSB.UsbFlashRead64(i + 0xc, ref flashi);
                                            if (flashi == four)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                kbyte *= 2;
                            }
                        }
                        else
                        {
                            for (uint i = 0x10000; i < 0x400000; i *= 2)
                            {
                                XChipUSB.UsbFlashRead86(i, ref flashi);
                                if (flashi == one)
                                {
                                    XChipUSB.UsbFlashRead86(i + 0x4, ref flashi);
                                    if (flashi == two)
                                    {
                                        XChipUSB.UsbFlashRead86(i + 0x8, ref flashi);
                                        if (flashi == three)
                                        {
                                            XChipUSB.UsbFlashRead86(i + 0xc, ref flashi);
                                            if (flashi == four)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                kbyte *= 2;
                            }
                        }
                        List<TreeListValue> list = new List<TreeListValue>();
                        list.Add(new TreeListValue() { DisplayMember = $"{kbyte}k", ValueMember = $"{kbyte * 1024}" });
                        list.Add(new TreeListValue() { DisplayMember = "4M", ValueMember = $"{4 * 1024 * 1024}" });
                        list.Add(new TreeListValue() { DisplayMember = "8M", ValueMember = $"{8 * 1024 * 1024}" });
                        comboBoxFlashSize.Properties.DataSource = list;
                        comboBoxFlashSize.Properties.ValueMember = "ValueMember";
                        comboBoxFlashSize.Properties.DisplayMember = "DisplayMember";

                        comboBoxFlashSize.ItemIndex = 0;
                    }
                    WaitBefore.Close();
                    //this.txtBoxFlashData.Text = Convert.ToString(recvdata, 16).ToUpper();
                    return;
                }
                if (!sPortTemp.IsOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("串口没有打开");
                    return;
                }
                //if (!Regex.Match(txtBoxFlashAddress.Text, @"^[A-Za-z0-9]+$").Success)
                //{
                //    return;
                //}
                ErasePrecent.EditValue = 0;
                Fb_SendEvent("Flash操作->读ReadID 执行开始\r\n");
                long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;

                uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
                uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

                test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
                uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

                test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
                uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

                test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
                uint TXD0_ADDR = (uint)(test_value1 + test_value2);

                test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
                uint TXD1_ADDR = (uint)(test_value1 + test_value2);


                test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
                uint RXD0_ADDR = (uint)(test_value1 + test_value2);

                test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
                uint RXD1_ADDR = (uint)(test_value1 + test_value2);

                uint spi_shift_cnt;
                uint spi_rxvld_cnt;
                uint senddata;
                uint recvdata = 0;
                uint op_code = 0x9f;
                //80200000 写 1
                FlashBase fb = new FlashBase(sPortTemp);
                fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
                fb.SendEvent += Fb_SendEvent;
                //spi cs 片选
                uint spi_cs = 1;
                //82000004 32位读
                fb.ReadRegDataARM(0x11, CONTROL_ADDR, ref recvdata, sPortTemp);

                senddata = recvdata & 0xffff3cff;
                senddata = senddata + (spi_cs << 8);
                //82000004  32位写82000004 32位读 & 0xffff3cff + (1 << 8)
                fb.SendRegDataARM(0x1, CONTROL_ADDR, senddata, sPortTemp);
                //TXD0
                senddata = op_code;
                //82000010 32位写 9F
                fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
                //SHIFT_CONTROL
                spi_shift_cnt = 64;
                spi_rxvld_cnt = 32;
                senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
                //8200000c 32位写  (3 << 16) + (32 << 8) + (64 << 0);
                fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);

                Thread.Sleep(200);
                //82000020 32位读得出结果

                fb.ReadRegDataARM(0x11, RXD0_ADDR, ref recvdata, sPortTemp);
                var kbytestr = (Math.Pow(2, (recvdata >> 16 & 0xff)) / 1024);
                if (kbytestr != 0xff && kbytestr != 0 && kbytestr % 1 == 0 && recvdata != 0xffffffff)
                {
                    List<TreeListValue> list = new List<TreeListValue>();
                    list.Add(new TreeListValue() { DisplayMember = $"{kbytestr}k", ValueMember = $"{kbytestr * 1024}" });
                    list.Add(new TreeListValue() { DisplayMember = "4M", ValueMember = $"{4 * 1024 * 1024}" });
                    list.Add(new TreeListValue() { DisplayMember = "8M", ValueMember = $"{8 * 1024 * 1024}" });
                    comboBoxFlashSize.Properties.DataSource = list;
                    comboBoxFlashSize.Properties.ValueMember = "ValueMember";
                    comboBoxFlashSize.Properties.DisplayMember = "DisplayMember";

                    comboBoxFlashSize.ItemIndex = 0;
                    WaitBefore.Close();
                    return;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                WaitBefore.Close();
            }

            try
            {
                WaitBefore.Start("请耐心等待...", "正在努力加载中");
                uint startone = 0x0;
                uint starttwo = 0x4;
                uint startthree = 0x8;
                uint startfour = 0xc;
                var one = FlashRead(startone);
                var two = FlashRead(starttwo);
                var three = FlashRead(startthree);
                var four = FlashRead(startfour);

                if (one == "FFFFFFFF"
                    && two == "FFFFFFFF"
                    && three == "FFFFFFFF"
                    && four == "FFFFFFFF")
                {
                    FlashWrite(startone, 0x00010203);
                    FlashWrite(starttwo, 0x04050607);
                    FlashWrite(startthree, 0x08090a0b);
                    FlashWrite(startfour, 0x0c0d0e0f);
                    one = "00010203";
                    two = "04050607";
                    three = "08090a0b";
                    four = "0c0d0e0f";
                }

                int kbyte = 64;
                one = FlashRead(startone);
                two = FlashRead(starttwo);
                three = FlashRead(startthree);
                four = FlashRead(startfour);
                if (one == "FFFFFFFF"
                     && two == "FFFFFFFF"
                     && three == "FFFFFFFF"
                     && four == "FFFFFFFF")
                {
                    Fb_SendEvent("Flash操作->容量检测失败 请先SPI使能\r\n");
                    return;
                }
                for (uint i = 0x10000; i < 0x400000; i *= 2)
                {
                    if (FlashRead(i) == one
                        && FlashRead(i + 0x4) == two
                        && FlashRead(i + 0x8) == three
                        && FlashRead(i + 0xc) == four)
                    {
                        break;
                    }
                    kbyte *= 2;
                }
                List<TreeListValue> list = new List<TreeListValue>();
                list.Add(new TreeListValue() { DisplayMember = $"{kbyte}k", ValueMember = $"{kbyte * 1024}" });
                list.Add(new TreeListValue() { DisplayMember = "4M", ValueMember = $"{4 * 1024 * 1024}" });
                list.Add(new TreeListValue() { DisplayMember = "8M", ValueMember = $"{8 * 1024 * 1024}" });
                comboBoxFlashSize.Properties.DataSource = list;
                comboBoxFlashSize.Properties.ValueMember = "ValueMember";
                comboBoxFlashSize.Properties.DisplayMember = "DisplayMember";

                comboBoxFlashSize.ItemIndex = 0;


            }
            catch (Exception)
            {

            }
            finally
            {
                WaitBefore.Close();
            }
        }

        private async void btnFullChipErase_Click(object sender, EventArgs e)
        {
            btnFullChipErase.Enabled = false;


            try
            {
                if (isI2C)
                {
                    WaitBefore.Start("请耐心等待...", "正在擦除中");
                    ErasePrecent.EditValue = 0;
                    Fb_SendEvent("Flash操作->整片擦除 执行开始\r\n");
                    simpleButton7_Click(null, null);
                    uint i2cflash_address = 0;
                    uint i2csenddata = 0;
                    uint i2cFlashSize = uint.Parse(comboBoxFlashSize.EditValue.ToString());
                    uint i2cFlash_Address_Total = i2cFlashSize;
                    while (i2cflash_address < i2cFlash_Address_Total)
                    {
                        i2csenddata = (((i2cflash_address & 0xff) << 24) + ((i2cflash_address & 0xff00) << 8) + ((i2cflash_address & 0xff0000) >> 8) + 0xD8);  //ERASE 64KB 
                        SerialSend.WriteRegister(0x82000013, i2csenddata >> 24 & 0xff, null);
                        SerialSend.WriteRegister(0x82000012, i2csenddata >> 16 & 0xff, null);
                        SerialSend.WriteRegister(0x82000011, i2csenddata >> 8 & 0xff, null);
                        SerialSend.WriteRegister(0x82000010, i2csenddata & 0xff, null);
                        i2csenddata = (3 << 16) + (0 << 8) + (32 << 0);

                        SerialSend.WriteRegister(0x8200000f, i2csenddata >> 24 & 0xff, null);
                        SerialSend.WriteRegister(0x8200000d, i2csenddata >> 8 & 0xff, null);
                        SerialSend.WriteRegister(0x8200000c, i2csenddata & 0xff, null);
                        SerialSend.WriteRegister(0x8200000e, i2csenddata >> 16 & 0xff, null);
                        i2cflash_address += 0x10000;
                        //需要添加休眠
                        Thread.Sleep(1000);
                        //进度条显示
                        Process_Display(i2cflash_address, i2cFlash_Address_Total);
                    }
                    Fb_SendEvent("Flash操作->整片擦除 执行成功\r\n");

                    WaitBefore.TopMostMessageBox.Show("整片擦除完毕！", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None);
                    return;
                }
                #region USB
                if (IsUsbOpen)
                {
                    //XChipUSB.UsbFlashWrite64(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), Convert.ToUInt32(txtBoxFlashData.Text, 16));
                    //XChipUSB.UsbFlashRead64(Convert.ToUInt32(txtBoxFlashAddress.Text, 16), ref pVule);

                    SerialSend.WriteRegister(0x82000010, 0x9f, sPortTemp);
                    SerialSend.WriteRegister(0x82000011, 0x00, sPortTemp);
                    SerialSend.WriteRegister(0x82000012, 0x00, sPortTemp);
                    SerialSend.WriteRegister(0x82000013, 0x00, sPortTemp);
                    Thread.Sleep(100);
                    SerialSend.WriteRegister(0x8200000c, 0x40, sPortTemp);
                    SerialSend.WriteRegister(0x8200000d, 0x20, sPortTemp);
                    SerialSend.WriteRegister(0x8200000e, 0x03, sPortTemp);
                    SerialSend.WriteRegister(0x8200000f, 0x00, sPortTemp);
                    Thread.Sleep(100);
                    var aaa = Convert.ToUInt32(((SerialSend.ReadRegister(0x82000023, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000022, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000021, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000020, sPortTemp)).ToString("X2")), 16);
                    var kbytestrUSB = (Math.Pow(2, (Convert.ToUInt32(((SerialSend.ReadRegister(0x82000023, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000022, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000021, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x82000020, sPortTemp)).ToString("X2")), 16) >> 16 & 0xff)) / 1024);
                    if (kbytestrUSB != 0xff && kbytestrUSB != 0 && kbytestrUSB % 1 == 0 && aaa != 0xffffffff)
                    {
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbFlashErase64(0);
                            for (int i = 1; i < kbytestrUSB; i++)
                            {
                                var aaaaaa = (uint)i * 1024;
                                XChipUSB.UsbFlashErase64((uint)i * 1024);
                            }


                        }
                        else
                        {
                            XChipUSB.UsbFlashErase86(0);
                            for (int i = 1; i < kbytestrUSB; i++)
                            {
                                XChipUSB.UsbFlashErase86((uint)i * 1024);
                            }
                        }

                        //List<TreeListValue> list = new List<TreeListValue>();
                        //list.Add(new TreeListValue() { DisplayMember = $"{kbytestrUSB}k", ValueMember = $"{kbytestrUSB * 1024}" });
                        //list.Add(new TreeListValue() { DisplayMember = "4M", ValueMember = $"{4 * 1024 * 1024}" });
                        //list.Add(new TreeListValue() { DisplayMember = "8M", ValueMember = $"{8 * 1024 * 1024}" });
                        //comboBoxFlashSize.Properties.DataSource = list;
                        //comboBoxFlashSize.Properties.ValueMember = "ValueMember";
                        //comboBoxFlashSize.Properties.DisplayMember = "DisplayMember";

                        //comboBoxFlashSize.ItemIndex = 0;
                        WaitBefore.Close();

                        DevExpress.XtraEditors.XtraMessageBox.Show("整片擦除完毕！");
                        return;
                    }
                    else
                    {
                        uint startone = 0x0;
                        uint starttwo = 0x4;
                        uint startthree = 0x8;
                        uint startfour = 0xc;
                        uint one = 0;
                        uint two = 0;
                        uint three = 0;
                        uint four = 0;
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbFlashRead64(startone, ref one);
                        }
                        else
                        {
                            XChipUSB.UsbFlashRead86(startone, ref one);
                        }
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbFlashRead64(starttwo, ref two);
                        }
                        else
                        {
                            XChipUSB.UsbFlashRead86(starttwo, ref two);
                        }
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbFlashRead64(startthree, ref three);
                        }
                        else
                        {
                            XChipUSB.UsbFlashRead86(startthree, ref three);
                        }
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbFlashRead64(startfour, ref four);
                        }
                        else
                        {
                            XChipUSB.UsbFlashRead86(startfour, ref four);
                        }
                        if (one.ToString("X2") == "FFFFFFFF"
                            && two.ToString("X2") == "FFFFFFFF"
                            && three.ToString("X2") == "FFFFFFFF"
                            && four.ToString("X2") == "FFFFFFFF")
                        {
                            FlashWrite(startone, 0x00010203);
                            FlashWrite(starttwo, 0x04050607);
                            FlashWrite(startthree, 0x08090a0b);
                            FlashWrite(startfour, 0x0c0d0e0f);
                            one = 0x00010203;
                            two = 0x04050607;
                            three = 0x08090a0b;
                            four = 0x0c0d0e0f;
                        }
                        int kbyte = 64;
                        uint flashi = 0;
                        if (IntPtr.Size == 8)
                        {

                            for (uint i = 0x10000; i < 0x400000; i *= 2)
                            {
                                XChipUSB.UsbFlashRead64(i, ref flashi);
                                if (flashi == one)
                                {
                                    XChipUSB.UsbFlashRead64(i + 0x4, ref flashi);
                                    if (flashi == two)
                                    {
                                        XChipUSB.UsbFlashRead64(i + 0x8, ref flashi);
                                        if (flashi == three)
                                        {
                                            XChipUSB.UsbFlashRead64(i + 0xc, ref flashi);
                                            if (flashi == four)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                kbyte *= 2;
                            }
                        }
                        else
                        {
                            for (uint i = 0x10000; i < 0x400000; i *= 2)
                            {
                                XChipUSB.UsbFlashRead86(i, ref flashi);
                                if (flashi == one)
                                {
                                    XChipUSB.UsbFlashRead86(i + 0x4, ref flashi);
                                    if (flashi == two)
                                    {
                                        XChipUSB.UsbFlashRead86(i + 0x8, ref flashi);
                                        if (flashi == three)
                                        {
                                            XChipUSB.UsbFlashRead86(i + 0xc, ref flashi);
                                            if (flashi == four)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                kbyte *= 2;
                            }
                        }
                        //List<TreeListValue> list = new List<TreeListValue>();
                        //list.Add(new TreeListValue() { DisplayMember = $"{kbyte}k", ValueMember = $"{kbyte * 1024}" });
                        //list.Add(new TreeListValue() { DisplayMember = "4M", ValueMember = $"{4 * 1024 * 1024}" });
                        //list.Add(new TreeListValue() { DisplayMember = "8M", ValueMember = $"{8 * 1024 * 1024}" });
                        //comboBoxFlashSize.Properties.DataSource = list;
                        //comboBoxFlashSize.Properties.ValueMember = "ValueMember";
                        //comboBoxFlashSize.Properties.DisplayMember = "DisplayMember";
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbFlashErase64(0);
                            for (int i = 1; i < kbyte; i++)
                            {
                                XChipUSB.UsbFlashErase64((uint)i * 1024);
                            }


                        }
                        else
                        {
                            XChipUSB.UsbFlashErase86(0);
                            for (int i = 1; i < kbyte; i++)
                            {
                                XChipUSB.UsbFlashErase86((uint)i * 1024);
                            }
                        }
                        //comboBoxFlashSize.ItemIndex = 0;
                    }
                    WaitBefore.Close();

                    DevExpress.XtraEditors.XtraMessageBox.Show("整片擦除完毕！");
                    //this.txtBoxFlashData.Text = Convert.ToString(recvdata, 16).ToUpper();
                    return;
                }
                #endregion

                if (!sPortTemp.IsOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("串口没有打开");
                    return;
                }
                simpleButton7_Click(null, null);
                WaitBefore.Start("请耐心等待...", "正在擦除中");
                ErasePrecent.EditValue = 0;
                Fb_SendEvent("Flash操作->整片擦除 执行开始\r\n");
                uint FlashSize = uint.Parse(comboBoxFlashSize.EditValue.ToString());
                uint Flash_Address_Total = FlashSize;

                long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;

                uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
                uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

                test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
                uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

                test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
                uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

                test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
                uint TXD0_ADDR = (uint)(test_value1 + test_value2);

                test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
                uint TXD1_ADDR = (uint)(test_value1 + test_value2);


                test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
                uint RXD0_ADDR = (uint)(test_value1 + test_value2);

                test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
                uint RXD1_ADDR = (uint)(test_value1 + test_value2);

                uint flash_address = 0;
                //uint flash_data = Convert.ToUInt32(txtBoxFlashData.Text, 16);

                uint spi_shift_cnt;
                uint spi_rxvld_cnt;
                uint senddata;
                uint recvdata = 0;

                FlashBase fb = new FlashBase(sPortTemp);
                fb.SendEvent += Fb_SendEvent;
                while (flash_address < Flash_Address_Total)
                {
                    fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
                    fb.FlashWriteEnable(sPortTemp);
                    recvdata = fb.FlashReadStatus(sPortTemp);

                    senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0x39);
                    fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);

                    spi_shift_cnt = 32;
                    spi_rxvld_cnt = 0;
                    senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
                    fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
                    Thread.Sleep(200);

                    recvdata = fb.FlashReadStatus(sPortTemp);
                    fb.FlashWriteEnable(sPortTemp);
                    recvdata = fb.FlashReadStatus(sPortTemp);

                    senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0xD8);  //ERASE 64KB 
                    fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);

                    spi_shift_cnt = 32;
                    spi_rxvld_cnt = 0;
                    senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
                    fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
                    flash_address += 0x10000;
                    //需要添加休眠
                    Thread.Sleep(1000);
                    //进度条显示
                    Process_Display(flash_address, Flash_Address_Total);
                }
                Fb_SendEvent("Flash操作->整片擦除 执行成功\r\n");
                
                WaitBefore.TopMostMessageBox.Show("整片擦除完毕！", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None);

            }
            catch (Exception)
            {

            }
            finally
            {
                WaitBefore.Close();
                btnFullChipErase.Enabled = true;
                //WaitBefore.CancelTask();
            }
           
        }
        private void Process_Display(uint flash_address, uint Flash_Address_Total)
        {
            this.Invoke((EventHandler)(delegate
            {
                if (flash_address == Flash_Address_Total)
                {
                    ErasePrecent.EditValue = Flash_Address_Total;
                }
                else
                {
                    if (ErasePrecent.Position != Flash_Address_Total)
                    {
                        //处理当前消息队列中的所有windows消息
                        Application.DoEvents();
                        //当前线程挂起指定的时间,这个是为了演示
                        System.Threading.Thread.Sleep(10);
                        //执行步长
                        ErasePrecent.PerformStep();
                    }
                }
            }));


        }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (IsUsbOpen || isI2C)
            {
                var Count = Convert.ToUInt32(((SerialSend.ReadRegister(0x2000151f, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x2000151e, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x2000151d, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x2000151c, sPortTemp)).ToString("X2")), 16);
                var Limit = Convert.ToUInt32(((SerialSend.ReadRegister(0x20001523, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x20001522, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x20001521, sPortTemp)).ToString("X2") + (SerialSend.ReadRegister(0x20001520, sPortTemp)).ToString("X2")), 16);
                if (Count == (Limit + 1))
                {
                    SerialSend.WriteRegister(0x80500137, 0xb1, sPortTemp);
                    Fb_SendEvent("解除写保护成功");
                }
                return;
            }
            //80500137 写0xb1
            if ((ReadStatusFlash() & 0x1c) == 0x1c)//是否处于写保护状态
            {//是
                DisableWriteProtect();
                byte status = ReadStatusFlash();
                if ((status & 0x1c) == 0x1c)//是否成功解除
                {
                    Fb_SendEvent("解除写保护失败");
                    simpleButton1.Text = "解除写保护";
                }
                else if ((status & 0x1c) == 0x00)
                {
                    Fb_SendEvent("解除写保护成功");
                    //simpleButton1.Text = "开启写保护";
                }
            }
            //else
            //{//否
            //    EnableWriteProtect();
            //    byte status = ReadStatusFlash();
            //    if ((status & 0x1c) == 0x1c)//是否成功
            //    {
            //        Fb_SendEvent("开启写保护成功");
            //        simpleButton1.Text = "解除写保护";
            //    }
            //    else if ((status & 0x1c) == 0x00)
            //    {
            //        Fb_SendEvent("开启写保护成功失败");
            //        simpleButton1.Text = "开启写保护";
            //    }
            //}
        }
        void DisableWriteProtect()
        {
            //WriteStatusRegister((byte)(ReadStatusFlash() & 0x7f));//srp0写0
            WriteStatusRegister((byte)(ReadStatusFlash() & 0xe3));
        }
        void EnableWriteProtect()
        {
            //WriteStatusRegister((byte)(ReadStatusFlash() & 0x7f));//srp0写0
            WriteStatusRegister((byte)(ReadStatusFlash() | 0x1c));
        }
        void WriteStatusRegister(byte nStatus)
        {
            uint spi_base_addr = (uint)BaseRegisterMap.SPI_BASE_ADDR;
            uint FUNCT_SEL_ADDR = spi_base_addr + (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint CONTROL_ADDR = spi_base_addr + (uint)SPIRegisterMap.SPI_CONTROL;
            uint RESERVED_ADDR = spi_base_addr + (uint)SPIRegisterMap.SPI_RESERVED;
            uint SHIFT_ADDR = spi_base_addr + (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            uint TXD0_ADDR = spi_base_addr + (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            uint spi_shift_cnt;
            uint spi_rxvld_cnt;
            uint senddata;

            //spi_enable
            simpleButton11_Click(null, null);
            SPI_Status_Clear();
            fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x01, sPortTemp);
            while ((ReadStatusFlash() & 0x01) == 0x01) ;
            fb.SendRegDataARM(0x1, TXD0_ADDR, 0x06, sPortTemp);
            spi_shift_cnt = 8;
            spi_rxvld_cnt = 0;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            SPI_WaitReady();
            while ((ReadStatusFlash() & 0x01) == 0x01) ;
            senddata = (uint)((nStatus << 8) + 0x01);
            SPI_Status_Clear();
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            spi_shift_cnt = 16;
            spi_rxvld_cnt = 0;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            SPI_WaitReady();
            while ((ReadStatusFlash() & 0x01) == 0x01) ;
        }
        private void SPI_Status_Clear()
        {
            uint BUSY_FM_ADDR;
            uint SPI_BUSY_FM = 0x40;
            BUSY_FM_ADDR = (uint)BaseRegisterMap.SPI_BASE_ADDR + SPI_BUSY_FM;

            #region BUSY_FM_ADDR写1 
            // /*  小端
            uint reg_address = BUSY_FM_ADDR;
            int byte_sel = (int)(reg_address) & 0x3;
            byte_sel = byte_sel * 8;
            uint reg_data = 1;
            reg_data = reg_data & 0xff;
            reg_data = reg_data << byte_sel;

            fb.SendRegDataARM(0x21, reg_address, reg_data, sPortTemp);
            #endregion

        }
        private void SPI_WaitReady()
        {
            uint time_out = 3;
            uint BUSY_ADDR;
            uint BUSY_FM_ADDR;
            uint test_value1 = (uint)BaseRegisterMap.SPI_BASE_ADDR;
            uint test_value2 = (uint)SPIRegisterMap.SPI_BUSY;
            BUSY_ADDR = test_value1 + test_value2;
            BUSY_FM_ADDR = test_value1 + (uint)SPIRegisterMap.SPI_BUSY_FM;

            uint data = 0;
            do
            {
                Thread.Sleep(10);
                fb.ReadRegDataARM(0x31, BUSY_FM_ADDR, ref data, sPortTemp);
            }
            while ((data != 2) && (time_out-- > 0));
            if (time_out <= 0)
            {
                MessageBox.Show("spi wait busy_status time out");
            }
        }
        private byte ReadStatusFlash()
        {
            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;
            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            uint TXD0_ADDR = (uint)(test_value1 + test_value2);
            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

            uint RXD0_ADDR = (uint)BaseRegisterMap.SPI_BASE_ADDR + (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
            fb = new FlashBase(sPortTemp);
            fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 1, sPortTemp);

            uint spi_shift_cnt;
            uint spi_rxvld_cnt;
            uint status = 0;
            uint op_code = 0x05;
            uint senddata = op_code;

            SPI_Status_Clear();
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            spi_shift_cnt = 16;
            spi_rxvld_cnt = 8;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            SPI_WaitReady();
            SPI_Status_Clear();
            fb.ReadRegDataARM(0x11, RXD0_ADDR, ref status, sPortTemp);
            return (byte)(status & 0xff);
        }
        private void simpleButton11_Click(object sender, EventArgs e)
        {
            if (isI2C)
            {
                Fb_SendEvent("SPI使能执行...\r\n");
                SerialSend.WriteRegister(0x805000F1, 0x55, sPortTemp);
                Fb_SendEvent(string.Format("SPI使能发送注册表数据完成\r\n"));
                Fb_SendEvent(string.Format("SPI使能执行完成\r\n"));
                return;
            }
            var isport = sPortTemp.IsOpen;
            if (!isport && !IsUsbOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请打开端口通讯！");
                return;
            }
            ErasePrecent.EditValue = 0;
            //long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;
            //uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            //uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            ////Fb_SendEvent(string.Format("SPI使能发送注册表数据...\r\n"));
            //fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0, sPortTemp);
            //Fb_SendEvent(string.Format("SPI使能发送注册表数据完成\r\n"));
            //fb.SendEvent += Fb_SendEvent;
            //Thread.Sleep(200);
            //Fb_SendEvent(string.Format("SPI使能读取注册表数据...\r\n"));
            //fb.ReadRegData(0x31, 0x80500200, ref recdata, sPortTemp);// 805000F1  0x55
            Fb_SendEvent("SPI使能执行...\r\n");
            //FlashBase fb = new FlashBase(sPortTemp);
            //var recdata = fb.ReadRegisterARM(0x31, 0x805000F1, sPortTemp);// 805000F1  0x55
            //Fb_SendEvent(string.Format("SPI使能读取注册表数据完成\r\n"));
            //recdata = (uint)recdata | 0x00000055U;

            //Fb_SendEvent(string.Format("SPI使能发送注册表数据...\r\n"));
            //fb.WriteRegisterARM(0x21, 0x805000F1, 0x55, sPortTemp);
            SerialSend.WriteRegister(0x805000F1, 0x55, sPortTemp);
            Fb_SendEvent(string.Format("SPI使能发送注册表数据完成\r\n"));
            Fb_SendEvent(string.Format("SPI使能执行完成\r\n"));
            //USB下也是805000F1地址写55
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            //读取文件  选择bin文件 读取bin文件长度  生成文件夹
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "Bin Files(*.bin)|*.bin|All Files(*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)//用户是否选择确定
            {
                textEdit1.Text = openFileDialog1.FileName;
            }
        }
        public static async Task<bool> WriteFileAsync(string fileName, uint startAddr, DevExpress.XtraEditors.ProgressBarControl progressBar)
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

            // 定义一个局部变量来捕获 progressBar，以便在回调中使用  
            DevExpress.XtraEditors.ProgressBarControl localProgressBar = progressBar;

            WriteFileCallBackType callback = (success, status) =>
            {
                // 更新进度条  
                if (localProgressBar.InvokeRequired)
                {
                    localProgressBar.Invoke((MethodInvoker)delegate
                    {
                        
                        if (status >= 0 && status <= 100 && success)
                        {
                            localProgressBar.Position = status;
                        }
                       
                    });
                }
                else
                {
                    if (status >= 0 && status <= 100)
                    {
                        localProgressBar.Position = status;
                    }
                }
                // 检查是否完成或失败  
                if (success && status == 100 || !success)
                {
                    tcs.SetResult(success);
                }
            };
            bool started = false;
            // 启动异步文件写入  
            if (IntPtr.Size == 8)
            {
                started = UsbFlashWriteFile64(fileName, startAddr, callback);
            }
            else
            {
                started = UsbFlashWriteFile86(fileName, startAddr, callback);
            }
            // 如果 UsbFlashWriteFile64 调用失败（例如，因为 DLL 加载失败），则直接设置 Task 为失败  
            if (!started)
            {
                tcs.SetException(new InvalidOperationException("调用 UsbFlashWriteFile64 失败"));
            }

            // 等待回调设置结果  
            return await tcs.Task;
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {

            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;

            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
            uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            uint TXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
            uint TXD1_ADDR = (uint)(test_value1 + test_value2);


            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
            uint RXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
            uint RXD1_ADDR = (uint)(test_value1 + test_value2);

            uint flash_address = 0;
            //uint flash_data = Convert.ToUInt32(txtBoxFlashData.Text, 16);

            uint spi_shift_cnt;
            uint spi_rxvld_cnt;
            uint senddata;
            uint recvdata = 0;

            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendEvent += Fb_SendEvent;
            fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
            fb.FlashWriteEnable(sPortTemp);
            recvdata = fb.FlashReadStatus(sPortTemp);

            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0x39);
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);

            spi_shift_cnt = 32;
            spi_rxvld_cnt = 0;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            Thread.Sleep(200);

            recvdata = fb.FlashReadStatus(sPortTemp);
            fb.FlashWriteEnable(sPortTemp);
            recvdata = fb.FlashReadStatus(sPortTemp);

            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0x60);  //ERASE 64KB 
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);

            spi_shift_cnt = 32;
            spi_rxvld_cnt = 0;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            flash_address += 0x10000;
            //需要添加休眠
            Thread.Sleep(1000);
        }

        public bool  SPI_Status()
        {
            bool isbool = false;
            for (int i = 0; i < 100; i++)
            {
                var aa = SerialSend.ReadRegister(0x82000040, null);
                if (aa == 0x02)
                {
                    isbool = true;
                    break;
                }
                Thread.Sleep(10);
            }
            return isbool;
        }

        public bool FlashReadStatus()
        {
            bool isbool = false;
            SerialSend.WriteRegister(0x82000013, 0x00, null);
            SerialSend.WriteRegister(0x82000012, 0x00, null);
            SerialSend.WriteRegister(0x82000011, 0x00, null);
            SerialSend.WriteRegister(0x82000010, 0x05, null);

            uint senddata = (3 << 16) + (8 << 8) + (16 << 0);
            SerialSend.WriteRegister(0x8200000f, senddata >> 24 & 0xff, null);
            SerialSend.WriteRegister(0x8200000d, senddata >> 8 & 0xff, null);
            SerialSend.WriteRegister(0x8200000c, senddata & 0xff, null);
            SerialSend.WriteRegister(0x8200000e, senddata >> 16 & 0xff, null);

            var value = SerialSend.ReadRegister(0x82000020, null);
            //需要判断返回的recvdata值bit0不为1才进行下一步(flash空闲）
            return (value & 1) != 1;
        }

        private string I2CFlashRead(uint flash_address)
        {
            uint senddata;
            uint op_code = 0x03;
            SerialSend.WriteRegister(0x82000000, 0x01, null);
            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + op_code);
            SerialSend.WriteRegister(0x82000013, senddata >> 24 & 0xff, null);
            SerialSend.WriteRegister(0x82000012, senddata >> 16 & 0xff, null);
            SerialSend.WriteRegister(0x82000011, senddata >> 8 & 0xff, null);
            SerialSend.WriteRegister(0x82000010, senddata & 0xff, null);
            Thread.Sleep(10);
            var aaaa = (3 << 16) + (32 << 8) + (64 << 0);
            //0x00032040
            SerialSend.WriteRegister(0x8200000f, (3 << 16) + (32 << 8) + (64 << 0) >> 24 & 0xff, null);
            SerialSend.WriteRegister(0x8200000d, (3 << 16) + (32 << 8) + (64 << 0) >> 8 & 0xff, null);
            SerialSend.WriteRegister(0x8200000c, (3 << 16) + (32 << 8) + (64 << 0) & 0xff, null);
            SerialSend.WriteRegister(0x8200000e, (3 << 16) + (32 << 8) + (64 << 0) >> 16 & 0xff, null);
            Thread.Sleep(10);

            for (int i = 0; i < 100; i++)
            {
                var aa = SerialSend.ReadRegister(0x82000040, null);
                if (aa == 0x02)
                {
                    break;
                }
                Thread.Sleep(10);
            }
            SerialSend.WriteRegister(0x82000040, 0x01, null);
            Thread.Sleep(10);
            var h = SerialSend.ReadRegister(0x82000023, null);
            var m1 = SerialSend.ReadRegister(0x82000022, null);
            var m0 = SerialSend.ReadRegister(0x82000021, null);
            var l = SerialSend.ReadRegister(0x82000020, null);
            Thread.Sleep(10);
            SerialSend.WriteRegister(0x82000040, 0x01, null);
            return h.ToString("X2") + m1.ToString("X2") + m0.ToString("X2") + l.ToString("X2");
        }
        private void I2CFlashWrite(uint flash_address, uint flash_data)
        {
            SerialSend.WriteRegister(0x82000013, 0x00, null);
            SerialSend.WriteRegister(0x82000012, 0x00, null);
            SerialSend.WriteRegister(0x82000011, 0x00, null);
            SerialSend.WriteRegister(0x82000010, 0x06, null);
            bool isbool = false;
            uint senddata = (3 << 16) + (0 << 8) + (8 << 0);
            SerialSend.WriteRegister(0x8200000f, senddata >> 24 & 0xff, null);
            SerialSend.WriteRegister(0x8200000d, senddata >> 8 & 0xff, null);
            SerialSend.WriteRegister(0x8200000c, senddata & 0xff, null);
            SerialSend.WriteRegister(0x8200000e, senddata >> 16 & 0xff, null);


            var h = SerialSend.ReadRegister(0x82000007, null);
            var m1 = SerialSend.ReadRegister(0x82000006, null);
            var m0 = SerialSend.ReadRegister(0x82000005, null);
            var l = SerialSend.ReadRegister(0x82000004, null);

            var recvdata = (uint)(h << 24 | m1 << 16 | m0 << 8 | l);
           
            isbool = SPI_Status();
            SerialSend.WriteRegister(0x82000040, 0x01, null);
            //FlashReadStatus();

            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + 0x02);
            SerialSend.WriteRegister(0x82000013, senddata >> 24 & 0xff, null);
            SerialSend.WriteRegister(0x82000012, senddata >> 16 & 0xff, null);
            SerialSend.WriteRegister(0x82000011, senddata >> 8 & 0xff, null);
            SerialSend.WriteRegister(0x82000010, senddata & 0xff, null);

            SerialSend.WriteRegister(0x82000017, flash_data >> 24 & 0xff, null);
            SerialSend.WriteRegister(0x82000016, flash_data >> 16 & 0xff, null);
            SerialSend.WriteRegister(0x82000015, flash_data >> 8 & 0xff, null);
            SerialSend.WriteRegister(0x82000014, flash_data & 0xff, null);
            senddata = (3 << 16) + (0 << 8) + (64 << 0);
            SerialSend.WriteRegister(0x8200000f, senddata >> 24 & 0xff, null);
            SerialSend.WriteRegister(0x8200000d, senddata >> 8 & 0xff, null);
            SerialSend.WriteRegister(0x8200000c, senddata & 0xff, null);
            SerialSend.WriteRegister(0x8200000e, senddata >> 16 & 0xff, null);
            isbool = SPI_Status();
            SerialSend.WriteRegister(0x82000040, 0x01, null);
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            // 创建 OpenFileDialog 的实例
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置文件类型过滤器
            openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            openFileDialog.Title = "打开 TXT 文件";

            // 显示对话框并判断用户是否选择了文件
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {


                try
                {
                    // 读取文件内容
                    PatchPath = openFileDialog.FileName;
                    // 获取文件名称并显示在 PatchLab 控件上
                    string fileName = Path.GetFileName(PatchPath);
                    PatchLab.Text = fileName; // 显示文件名称
                }
                catch (Exception ex)
                {
                    MessageBox.Show("无法打开文件: " + ex.Message);
                }
            }
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            // 创建 OpenFileDialog 的实例
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置文件类型过滤器
            openFileDialog.Filter = "Text Files (*.bin)|*.bin|All Files (*.*)|*.*";
            openFileDialog.Title = "打开 TXT 文件";

            // 显示对话框并判断用户是否选择了文件
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {


                try
                {
                    // 读取文件内容
                    string filePath = openFileDialog.FileName;
                    BinPath = filePath;
                    // 获取文件名称并显示在 PatchLab 控件上
                    string fileName = Path.GetFileName(filePath);
                    BinLab.Text = fileName; // 显示文件名称

                }
                catch (Exception ex)
                {
                    MessageBox.Show("无法打开文件: " + ex.Message);
                }
            }
        }
        private void UpdateProgress(int index)
        {
            if (InvokeRequired)
            {
                // 确保在 UI 线程上更新 ProgressBar
                this.Invoke(new Action<int>(UpdateProgress), index);
            }
            else
            {
                // 更新 ProgressBar 的值
                proBar.Value = index + 1;
            }
        }
        private void SetShowMsg(string msg)
        {
            if (isShowMsg)
            {
                this.textBox_disp.Invoke((EventHandler)(delegate
                {
                    //if (txtMsg.Text.Length > 10000)
                    //{
                    //    txtMsg.Text = "";
                    //}
                    //追加的形式添加到文本框末端，并滚动到最后。     
                    this.textBox_disp.AppendText($"{msg}\r\n");
                    this.textBox_disp.SelectionStart = textBox_disp.Text.Length;
                    this.textBox_disp.ScrollToCaret();

                }));
            }

        }
        private void I2CManager_OnMsgProcessed(string Msg)
        {
            isShowMsg = true;
            SetShowMsg(Msg);
        }

        private void simpleButton2_Click_1(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(BinPath) && string.IsNullOrEmpty(PatchPath))
            {
                MessageBox.Show("缺少Bin或者Patch 文件  请检查！");
                return;
            }
            if (string.IsNullOrEmpty(SerialSend.i2cid.ToString("X2")))
            {
                MessageBox.Show("未检测到选中的设备ID 请检查！");
                return;
            }

            isShowMsg = true;


            proBar.Value = 0;
            var deviceNo = Convert.ToByte(Convert.ToInt32(SerialSend.i2cid.ToString("X2"), 16));
            I2CManager i2CManager = new I2CManager(mIndex);
            i2CManager.OnIndexProcessed += UpdateProgress;
            i2CManager.OnMsgProcessed += I2CManager_OnMsgProcessed;

            //if (!i2CManager.IsDevicePresent(deviceNo))
            //{
            //    MessageBox.Show("检测到设备不在线");
            //    return;
            //}
            // 获取桌面路径
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            // 定义输出文件路径
            string outputPath = Path.Combine(desktopPath, "RAddresses.txt");
            string inputPath = Path.Combine(desktopPath, "ParsedAddresses.txt");

            byte[] readData;
            byte[] readData1;
            i2CManager.SendI2CData(0x80500137, new List<uint> { 0x66 }, deviceNo);
            Thread.Sleep(100);
            i2CManager.GetI2CData(0x80500137, deviceNo, 1, out readData);
            if (null == readData || readData[0] != 0x88)
            {
                MessageBox.Show("请断电重启设备！检查无法烧入");
                return;
            }

            //0x36 burst
            i2CManager.SendI2CData(0x80251000, new List<uint> { 0x01 }, deviceNo);
            SetShowMsg($"W:0x{0x80251000:X4} ,0x{0x01:X2} length 1");
            //添加tve 烧写功能 iic burst    0x38 burst
            i2CManager.SendI2CData(0x80250000, new List<uint> { 0x81 }, deviceNo);
            SetShowMsg($"W:0x{0x80250000:X4} ,0x{0x81:X2} length 1");




            i2CManager.GetI2CData(0x80500139, deviceNo, 1, out readData);
            i2CManager.GetI2CData(0x80500133, deviceNo, 1, out readData1);
            SetShowMsg($"0x80500139,0x{readData[0]:X}  0x80500133,0x{readData1[0]:X} ");
            byte[] readData2;
            byte[] readData3;
            i2CManager.GetI2CData(0x20006e33, deviceNo, 1, out readData2);
            i2CManager.GetI2CData(0x20006e34, deviceNo, 1, out readData3);
            if ((readData[0] != 0xde && readData1[0] != 0xef) || (readData2[0] == 0x0 || readData3[0] == 0x0))
            {
                i2CManager.SendI2CData(0x2000000c, new List<uint> { 0x0, 0x0, 0x0, 0x0 }, deviceNo);
                Thread.Sleep(1000);
                // 解析文件内容
                List<ParsedData> parsedDataList = i2CManager.ParseAddresses(BinPath);
                StringBuilder sbOp = new StringBuilder();


                foreach (var parsedData in parsedDataList)
                {
                    i2CManager.SendI2CData(parsedData.address, parsedData.values, deviceNo);
                    if (parsedData.address >= 0x20007e00 && parsedData.address < 0x20009000)
                    {
                        // 验证并记录
                        for (uint offset = 0; offset < parsedData.values.Count; offset++)
                        {
                            uint currentAddr = parsedData.address + offset;
                            if (!GetI2CData(currentAddr, deviceNo, 1, out readData))
                            {
                                SetShowMsg($"地址 0x{currentAddr:X8} 读取失败");
                                return;
                            }
                            if (parsedData.values[Convert.ToInt32(offset)] != readData[0])
                            {
                                SetShowMsg("--->>>执行了Patch文件烧写！输入文件和输出文件内容不一致<<<<---");
                                return;
                            }
                            sbOp.Append($"0x{currentAddr:X8},0x{readData[0]:X2}");
                            //writer.WriteLine($"0x{currentAddr:X8},0x{readData[0]:X2}");
                        }

                    }
                }


                using (var writer = new StreamWriter(outputPath, false)) // true 表示追加写入
                {
                    writer.WriteLine(sbOp.ToString());

                }

                SetShowMsg($"--->>>执行了Patch文件烧写！<<<<---");
                //Thread.Sleep(1000);
                //i2CManager.SendI2CData(0x80500137, new List<uint> { 0x66 }, deviceNo);
                //Thread.Sleep(1000);
                //i2CManager.GetI2CData(0x80500137, deviceNo, 1, out readData);
                //if (readData[0] != 0x88)
                //{
                //    MessageBox.Show("请断电重启设备！检查无法烧入");
                //    return;
                //}
            }

            Thread.Sleep(100);
            // 记录程序开始时间
            DateTime startTime = DateTime.Now;
            // 解析文件
            List<ParsedData> parsedBinDataList = i2CManager.ParseBinAddresses(BinPath);
            // 初始化 ProgressBar
            proBar.Minimum = 0;
            proBar.Maximum = parsedBinDataList.Count;
            i2CManager.SendDataToBuffers(parsedBinDataList, deviceNo);

            // 烧录完成是否需要软复位标记位:0x32需要进行复位
            i2CManager.SendI2CData(0x20001461, new List<uint> { 0x32 }, deviceNo);


            // 记录程序结束时间
            DateTime endTime = DateTime.Now;
            // 计算运行时间
            TimeSpan runTime = endTime - startTime;

            // 提示用户烧写完成，并输出运行时间
            MessageBox.Show($"完成Bin烧写！！！\n程序运行时间：{runTime.TotalSeconds:F2}秒  ");
        }
        /// 获取 I2C 数据
        /// </summary>
        /// <param name="subB">用于构建 I2C 数据的参数</param>
        /// <param name="deviceNo">设备编号</param>
        /// <param name="readLength">要读取的数据长度</param>
        /// <param name="readData">输出读取的数据</param>
        /// <returns>成功获取返回 true，失败返回 false</returns>
        public bool GetI2CData(uint subB, byte deviceNo, int readLength, out byte[] readData)
        {
            readData = null; // 初始化输出参数

            // 检查 readLength 是否为正值
            if (readLength <= 0)
            {
                return false; // 无效的读取长度，返回失败
            }

            // 如果 subB 是 16 位，则处理特殊情况
            if (subB <= 0xFFFF)
            {
                byte[] wbuffer = new byte[3];
                byte[] rbuffer = new byte[readLength]; // 用于保存读取的数据

                wbuffer[0] = deviceNo; // 第一个字节为设备地址
                wbuffer[1] = Convert.ToByte((subB >> 8) & 0xff); // 高字节
                wbuffer[2] = Convert.ToByte(subB & 0xff); // 低字节

                // 发送 I2C 数据并读取返回的数据
                if (USBIOXdll.USBIO_StreamI2C(mIndex, Convert.ToUInt32(wbuffer.Length), wbuffer, Convert.ToUInt32(rbuffer.Length), rbuffer))
                {
                    readData = rbuffer; // 返回读取的数据
                    return true; // 成功获取数据
                }
                else
                {
                    return false; // 获取数据失败
                }
            }

            // 处理 32 位 subB 的情况
            // 发送高字节
            if (!SendI2CSubBByte(deviceNo, (byte)((subB >> 24) & 0xff), 0xfd))
            {
                return false; // 发送高字节失败
            }

            // 发送中高字节
            if (!SendI2CSubBByte(deviceNo, (byte)((subB >> 16) & 0xff), 0xfe))
            {
                return false; // 发送中高字节失败
            }

            // 准备读取数据
            byte[] wbuffer32 = new byte[3];
            byte[] rbuffer32 = new byte[readLength]; // 用于保存读取的数据

            wbuffer32[0] = deviceNo; // 设备地址
            wbuffer32[1] = Convert.ToByte((subB >> 8) & 0xff); // 高字节
            wbuffer32[2] = Convert.ToByte(subB & 0xff); // 低字节

            // 发送 I2C 数据并读取返回的数据
            if (USBIOXdll.USBIO_StreamI2C(mIndex, Convert.ToUInt32(wbuffer32.Length), wbuffer32, Convert.ToUInt32(rbuffer32.Length), rbuffer32))
            {
                readData = rbuffer32; // 返回读取的数据
                return true; // 成功获取数据
            }
            else
            {
                return false; // 获取数据失败
            }
        }
        private bool SendI2CSubBByte(byte deviceNo, byte dataByte, byte controlByte)
        {
            byte[] fdbuf = new byte[4]
            {
               deviceNo,  // 设备编号
               0xff,       // 根据实际需要设置
               controlByte,// 控制字节
               dataByte    // 数据字节
            };

            return USBIOXdll.USBIO_StreamI2C(mIndex, Convert.ToUInt16(fdbuf.Length), fdbuf, 0, null);
        }
    }
}
